
import urllib,sys
#这个不会导子模块就离谱
import urllib.parse
import urllib.request
import ssl
import base64
import json
import os
import time
import shutil

#   python2 是真的难用，头秃

host = 'https://dongwu.market.alicloudapi.com'
path = '/do'
method = 'POST'
appcode = 'bfaa11c5fda349efae5aeb8bc42f4b2d'
querys = ''
bodys = {}
url = host + path
imgs = os.listdir("H:\学习\研究生\动物识别\\test")
imgNum = len(imgs)

for i in range (imgNum):
    start = time.time()
    #图片所在的相对路径，单纯为了短··也可以用上面的绝对路径拼接
    file= "test/"+imgs[i]
    f = open(file, 'rb')
    img = base64.b64encode(f.read())
    bodys['baike'] = '''0'''
    bodys['image'] = img
    bodys['num'] = '''6'''
    post_data = urllib.parse.urlencode(bodys).encode("utf-8")
    request = urllib.request.Request(url, post_data)
    request.add_header('Authorization', 'APPCODE ' + appcode)
    # 根据API的要求，定义相对应的Content-Type
    request.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    response = urllib.request.urlopen(request, context=ctx)
    #这里读出来是byte类型，要通过解码来改成str类型
    content = response.read().decode()
    if (content):
        print (type(content))
        print(content)
        # result = content["result"]
        # result0 = result[0]
        # jpgname = result0["name"]
        # 输出文件图片的位置及图片ing

        shutil.copyfile(file, "test-xian/" + imgs[i].split("(",1)[0] + "-" + content.split("\"name\":\"")[1].split("\",\"score\"")[0] + ".jpg")
    end = time.time()
    print("Execution Time: ", end - start)